package com.best.weiyi.main;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

import com.best.lrc.WorkView;
import com.best.weiyi.R;
import com.best.weiyi.fragment.BestNew;
import com.best.weiyi.fragment.Me;
import com.best.weiyi.fragment.MusicList;
import com.best.weiyi.fragment.Search;
import com.best.weiyi.util.NetworkUtil;

public class MainActivity extends FragmentActivity implements OnClickListener{
	public static Way way;
	Button bestNew,musicList,search,me;
	//使用fragment组件
	FragmentManager fm;
	FragmentTransaction ft;
	
	//播放 暂停 下一曲 上一曲
	public static ImageView up,playAndPause,next;
	
	//进度条
	public static SeekBar sb;
	//总进度
	public static int pubProgress = 0;
	public static boolean isPause = true;
	//线程池(单线程)
	public static Executor executor = Executors.newFixedThreadPool(1);
	
	//viewPager
	ViewPager viewPager;
	List<View> viewList;
	
	//通知
	public NotificationManager nm;
	
	//电话状态
	private boolean mResumeAfterCall = false;
	
	//歌词部分
	ImageView lrc;
	public AlertDialog alert;
	public AlertDialog.Builder buider;
	Button but_stop;
	private WorkView workView;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//实例化Way类   可以直接使用
		way = new Way(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);		
		
		//判断网络   Activity创建即判断网络
		if(NetworkUtil.isNetWorkAvailable(this)){
			if(NetworkUtil.getCurrentNetType(this) != null){
				Toast.makeText(this, NetworkUtil.getCurrentNetType(this), Toast.LENGTH_LONG).show();
			}	
		}else{
			Toast.makeText(this, "无网络连接", Toast.LENGTH_LONG).show();
		}
		
		//找到组件
		bestNew = (Button) findViewById(R.id.bestNew);
		musicList = (Button) findViewById(R.id.musicList);
		search = (Button) findViewById(R.id.search);
		me = (Button) findViewById(R.id.me);
		bestNew.setOnClickListener(this);
		musicList.setOnClickListener(this);
		search.setOnClickListener(this);
		me.setOnClickListener(this);
		//开始进入时的界面
		if(savedInstanceState == null){
			fm = getSupportFragmentManager();
			//开启事务
			ft = fm.beginTransaction();
			musicList.setBackgroundColor(Color.rgb(124,158,64));
			MusicList musicList = new MusicList();
			ft.add(R.id.fragment, musicList,"musicList");
			ft.commit();
		}
		
		//点击进行播放等一些动作
		up = (ImageView) findViewById(R.id.up);
		playAndPause = (ImageView) findViewById(R.id.playAndPause);
		next = (ImageView) findViewById(R.id.next);
		up.setOnClickListener(this);
		playAndPause.setOnClickListener(this);
		next.setOnClickListener(this);
		
		//歌词
		//lrc = (ImageView) findViewById(R.id.list_lrc);
		
		//进度条
		sb = (SeekBar) findViewById(R.id.musicSeek);
		sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean user) {
				// TODO Auto-generated method stub
				pubProgress = arg1;
				if(user){
					way.seekBarTo(arg1);
				}
			}
		});
		
		/*//ViewPager
		LayoutInflater mInflater = getLayoutInflater().from(this);
		View vBestNews = mInflater.inflate(R.layout.bestnew_fragment, null);
		View vMusicList = mInflater.inflate(R.layout.musiclist_fragment, null);
		View vSesarch = mInflater.inflate(R.layout.search_fragment, null);
		View vMe = mInflater.inflate(R.layout.me_fragment, null);
		//添加页面数据
		viewList = new ArrayList<View>();
		viewList.add(vBestNews);
		viewList.add(vMusicList);
		viewList.add(vSesarch);
		viewList.add(vMe);
		//实例化适配器
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		viewPager.setAdapter(new ViewPagerAdapter(null, viewList));
		viewPager.setCurrentItem(1); //设置默认当前页
		*/
		
		//Activity创建时，发送通知
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notificationss();
		
		//监听电话状态
		@SuppressWarnings("unused")
		PhoneStateListener mPhoneStateListener = new PhoneStateListener(){
			@Override
			 public void onCallStateChanged(int state, String incomingNumber) {
				 if(state == TelephonyManager.CALL_STATE_RINGING){
					 AudioManager mAudio = (AudioManager) getSystemService(AUDIO_SERVICE);
					 int ringvolume = mAudio.getStreamVolume(AudioManager.STREAM_RING);
					 if(ringvolume > 0){
						 //mResumeAfterCall = mResumeAfterCall;
						 way.pause();
					 }
				 }else if(state == TelephonyManager.CALL_STATE_OFFHOOK){
					 way.pause();
				 }else if(state == TelephonyManager.CALL_STATE_IDLE){
					 if(mResumeAfterCall){
						 way.play();
					 }
				 }
			 }
		};

		System.out.println("---------------------------------------");
		
	}
	@SuppressWarnings("static-access")
	@Override                                     
	public void onClick(View arg0) {
		ft = fm.beginTransaction();
		if(arg0.getId() == R.id.bestNew || arg0.getId() == R.id.musicList
				|| arg0.getId() == R.id.search || arg0.getId() == R.id.me
				|| arg0.getId() == R.id.lrc ){
			
			if(fm.findFragmentByTag("bestNew") != null){
				ft.hide(fm.findFragmentByTag("bestNew"));
			}
			if(fm.findFragmentByTag("musicList") != null){
				ft.hide(fm.findFragmentByTag("musicList"));
			}
			if(fm.findFragmentByTag("search") != null){
				ft.hide(fm.findFragmentByTag("search"));
			}
			if(fm.findFragmentByTag("me") != null){
				ft.hide(fm.findFragmentByTag("me"));
			}
			if(fm.findFragmentByTag("lrc") != null){
				ft.hide(fm.findFragmentByTag("lrc"));
			}
		}
		switch (arg0.getId()) {
		//最新
		case R.id.bestNew:
			//当按钮被点击时，改变背景颜色
			bestNew.setBackgroundColor(Color.rgb(124,158,64));
			musicList.setBackgroundColor(Color.WHITE);
			search.setBackgroundColor(Color.WHITE);
			me.setBackgroundColor(Color.WHITE);
			
			if(fm.findFragmentByTag("bestNew") != null){
				ft.show(fm.findFragmentByTag("bestNew"));
			}else{
				BestNew bestNew = new BestNew();
				ft.add(R.id.fragment, bestNew,"bestNew");
			}
			break;
			//歌单
		case R.id.musicList:
			musicList.setBackgroundColor(Color.rgb(124,158,64));
			bestNew.setBackgroundColor(Color.WHITE);
			search.setBackgroundColor(Color.WHITE);
			me.setBackgroundColor(Color.WHITE);
			
			if(fm.findFragmentByTag("musicList") != null){
				ft.show(fm.findFragmentByTag("musicList"));
			}else{
				MusicList musicList = new MusicList();
				ft.add(R.id.fragment,  musicList,"musicList");
			}
			break;
			//搜索
		case R.id.search:
			search.setBackgroundColor(Color.rgb(124,158,64));
			musicList.setBackgroundColor(Color.WHITE);
			bestNew.setBackgroundColor(Color.WHITE);
			me.setBackgroundColor(Color.WHITE);
			
			if(fm.findFragmentByTag("search") != null){
				ft.show(fm.findFragmentByTag("search"));
			}else{
				Search search = new Search();
				ft.add(R.id.fragment,search,"search");
			}
			break;
			//我
		case R.id.me:
			me.setBackgroundColor(Color.rgb(124,158,64));
			musicList.setBackgroundColor(Color.WHITE);
			search.setBackgroundColor(Color.WHITE);
			bestNew.setBackgroundColor(Color.WHITE);
			
			if(fm.findFragmentByTag("me") != null){
				ft.show(fm.findFragmentByTag("me"));
			}else{
				Me me = new Me();
				ft.add(R.id.fragment, me,"me");
			}
			break;
			
			//上一曲     
		case R.id.up:
			
			playAndPause.setImageDrawable(getResources().getDrawable(R.drawable.alarm_pause_btn));
			//进度清零
			pubProgress = 0;
			//sb.setMax((int) way.music.get(way.index).getTime());
			sb.setProgress(pubProgress);
			way.theLastOne();
			break;
			//下一曲
		case R.id.next:
			
			playAndPause.setImageDrawable(getResources().getDrawable(R.drawable.alarm_pause_btn));
			pubProgress = 0;
			sb.setProgress(pubProgress);
			way.theNextOne();
			break;
			//播放 暂停
		case R.id.playAndPause:
			//String path = w.list.get(w.index).getUrl();
			if(way.player.isPlaying()){
				way.pause();
				hanlder.removeCallbacks(run);
				//切换播放图标
				playAndPause.setImageDrawable(getResources().getDrawable(R.drawable.alarm_play_btn));
			}else{
				way.play();
				hanlder.post(run);
				playAndPause.setImageDrawable(getResources().getDrawable(R.drawable.alarm_pause_btn));
			}
			break;

		default:
			break;
		}
		ft.commit();
	}
	/**
	 * Handler控制进度条
	 * */
	public static Handler hanlder = new Handler();
	public static Runnable run = new Runnable() {	
		@Override
		public void run(){
			// TODO Auto-generated method stub
			pubProgress += 500; 
			sb.setProgress(pubProgress);
			hanlder.postDelayed(run, 500);
		}
	};
	/**
	 * 通知
	 */
	@SuppressWarnings("deprecation")
	public void Notificationss(){		
		 Notification n = new Notification();
		 n.icon = R.drawable.ic_launcher;//设置图标
		 n.tickerText = "用心倾听那一份宁静";//设置通知栏显示的文字
		 n.when = System.currentTimeMillis();//设置通知栏显示的时间
		 n.sound = Uri.parse("url");//设置通知的声音
		 
		 
		//在内部设置一个延迟的Intent 用来在通知点击事件时要做的操作 
		 Intent intent = new Intent(Intent.ACTION_MAIN); 
		 intent.addCategory(Intent.CATEGORY_LAUNCHER); 
		 
		 intent.setClass(this, MainActivity.class); 
		 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		 
		 n.flags = Notification.FLAG_ONGOING_EVENT; // 设置常驻 Flag
		 
		 PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
		 n.setLatestEventInfo(getApplicationContext(),"用心聆听那一份宁静", "", pIntent);
		 //创建远程视图布局RemoteViews
		 /*RemoteViews views = new RemoteViews(getPackageName(),R.layout.notification_activity);
		 n.contentView = views;*/
		 
		 nm.notify(R.drawable.ic_launcher, n);
		 
	}
	
	//点击出现Dialog，内含歌词
	public void lrcDialog(View v){
		SelectDialog selectDialog = new SelectDialog(this,R.style.selectorDialog);//创建Dialog并设置样式主题
		Window win = selectDialog.getWindow();
		LayoutParams params = new LayoutParams();
		//params.x = -80;//设置x坐标
		//params.y = -60;//设置y坐标
		win.setAttributes(params);
		selectDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
		selectDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		selectDialog.show();
		
	}
	/**
	 * 创建
	 * @author jingang
	 *
	 */
	class SelectDialog extends AlertDialog{

		public SelectDialog(Context context, int theme) {
		    super(context, theme);
		}
		
		public SelectDialog(Context context) {
		    super(context);
		}

		@Override  
		protected void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.show_lrc_activity);
		}
		}
	
}
